package com.nuanshui.heatedloan.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.constant.UserAuthType;
import com.nuanshui.heatedloan.dal.IdTypeHandler;
import com.nuanshui.heatedloan.entity.cms.security.*;
import com.nuanshui.heatedloan.service.cms.ServiceException;
import com.nuanshui.heatedloan.service.cms.security.*;
import com.nuanshui.heatedloan.userinfo.facade.UserAuthService;
import com.nuanshui.heatedloan.util.SecurityConstants;
import com.nuanshui.heatedloan.util.dwz.DwzPage;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 用户管理控制器
 */
@Controller
@RequestMapping("/cms/manage/user")
public class ApiUserController extends ApiController {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private AdminUserService userService;

	@Autowired
	UserRoleService userRoleService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private OrganizationService organizationService;
	
	@Autowired
	private  ApiUserService  apiUserService;
	
	@Autowired
	private ApiUserRoleService apiUserRoleService;
	
	@Autowired
	private ApiRoleService apiRoleService;
	
	@Autowired
	private FrontUserService frontUserService;
	
	@Reference(url=GlobalParam.USER_DUBBO_SERVER,timeout=GlobalParam.DUBBO_SERVER_TIME_OUT,version = GlobalParam.USER_DUBBO_SERVER_VERSION)
	private UserAuthService userAuthService;

	/**
	 * 保存新用户
	 * 
	 * @param user
	 * @return
	 */
	// @RequiresPermissions("User:save")
	@RequestMapping(value = "/create", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String create( final User user) {
		user.setCreateTime(new Date());
		try {
			userService.save(user);
		} catch (final ServiceException e) {
			log.error("添加新用户失败", e);
			return fail();
		}
		return success();
	}

	/**
	 * 修改用户
	 */
	// @RequiresPermissions("User:edit")
	@RequestMapping(value = "/updateInfo", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String update(@ModelAttribute("preloadUser") User user) {
		try {
			userService.update(user);
		} catch (final ServiceException e) {
			log.error("修改用户信息失败", e);
			return fail();
		}
		return success();
	}
	@ModelAttribute("preloadUser")
	public User getOne(
			@RequestParam(value = "id", required = false) final Long id) {
		if (id != null) {
			return userService.get(id);
		}
		return null;
	}

	/*
	 * @ModelAttribute("preloadUser") public User getOne(@RequestParam(value =
	 * "id", required = false) final Long id) { if (id != null) { return
	 * userService.get(id); } return null; }
	 */

	/**
	 * 删除用户
	 */
	// @RequiresPermissions("User:delete")
	@RequestMapping(value = "/delete", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String delete( final String id) {
		String failReason = "";
		try {
			if(StringUtils.isEmpty(id)) return success();
			String strs[]= id.split(",");
			for(String str :strs){
				long itemId = Long.parseLong(str);
				
				User user = userService.get(itemId);
				if(user.getDefaultUser() != null && user.getDefaultUser() == 1){//默认用户
					failReason = "默认用户不允许删除~";
				}else{
					//查看当前用户是否是一个展馆管理员，如果是，则删除权限。
					if(StringUtils.isNotEmpty(user.getMuseumId())){
						String frontUserIdStr = IdTypeHandler.encode(userService.loadFrontUserIdByAdminUserId(itemId));
						
						//删除后端用户
						userService.deleteAdminUserByFrontUserId(frontUserIdStr);
						userAuthService.delAuth(frontUserIdStr, UserAuthType.USERAUTHTYPE_MUSEUM_ADMIN);//删除权限
						
					}else{//否则既不是默认用户，也不是展馆管理员用户则直接删除
						userService.deleteById(itemId);
					}
				}
			}
			
		} catch (final ServiceException e) {
			log.error("删除用户失败", e);
			return fail();
		}
		
		return StringUtils.isNotEmpty(failReason) ? fail(failReason) : success();
	}


	/**
	 * 返回用户列表
	 */
	// @RequiresPermissions("User:view")
	@RequestMapping(value = "/list", method = { RequestMethod.GET,RequestMethod.POST }, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String list(final DwzPage page, final HttpServletRequest request, final String isSearch, String query) {
		List<UserVO> users = null;
		
		if(DEFAULTQUERYSTR.equals(query)|| StringUtils.isEmpty(query)){
			users = apiUserService.findAll(page);
		}else{
			UserVO user = JSON.parseObject(query, UserVO.class);
			if(!query.contains("status")){
				user.setStatus(null);
			}
			users = apiUserService.findAll(page, user);
		}
		 
		// 查询到的users没有设置userRole属性 需进一步处理
		for (UserVO user : users) {
			List<UserRoleVO> userRoleVOs = apiUserRoleService.find(user.getId());
			// userRole里面的role未设置 下一步完善
			for (UserRoleVO vo : userRoleVOs) {
			//	RoleVO roleVO = new RoleVO();
				RoleVO	roleVO = apiRoleService.findById(vo.getRoleId());
				if(roleVO != null){
					List<String> permissionList = apiUserService.findPermissionsByRoleId(vo.getRoleId());
					vo.setRole(roleVO);
					vo.getRole().setPermissionList(permissionList);
				}
			}

			user.setUserRoles(userRoleVOs);
		}
		
		final Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", users);
		map.put("total", page.getTotalCount());
		return success(  map, SerializerFeature.DisableCircularReferenceDetect);
	}

	/**
	 * 重置密码和更新状态
	 */
	//@RequiresPermissions("User:edit")
	@RequestMapping(value = "/reset/{type}/{userId}", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String reset(@PathVariable final String type, @PathVariable final Long userId) {
		final User user = userService.get(userId);
		if (type.equals("password")) {
			user.setPlainPassword("123456");
			return success();
		} else if (type.equals("status")) {
			if (user.getStatus().equals("enabled")) {
				user.setStatus("disabled");
			} else {
				user.setStatus("enabled");
			}
		}
		userService.update(user);
		return success();
	}

	/**
	 * 添加角色
	 * 
	 * @param userRole
	 */
//	@RequiresPermissions("User:save")
	@RequestMapping(value = "/create/userRole", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String createUserRole(final UserRole userRole) {
		userRoleService.save(userRole);
		return success();
	}
	
	/**
	 * 修改用户角色
	 * @param userId
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value="/assignRole",method=RequestMethod.POST ,produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String assignRole(Long userId, String roleId){
		
		//查看当前用户是否有默认的展馆管理角色
		boolean hasDefaultRole = false;
		List<UserRole> userRoles = userRoleService.find(userId);
		for(UserRole userRole : userRoles){
			if(userRole.getRole().getId() == -1){
				hasDefaultRole = true;
			}
		}
		String moreInfo = "";
		
		String roles[]= roleId.split(",");
        List<Integer> list=new ArrayList<Integer>();
		for(String str :roles){
			int itemId = Integer.parseInt(str);
			
			if(hasDefaultRole){//如果有一个默认的展馆管理角色
				list.add(itemId);//则虽然有-1这个权限，也添加进来
			}else{
				if(itemId != -1){
					list.add(itemId);
				}else{
					moreInfo = "展馆管理角色只能通过分配展馆进行分配~";
				}
			}
		}

		userService.updateRoles( userId, list);
		
		return StringUtils.isEmpty(moreInfo) ?  success() : fail(moreInfo);
		
	}

	/**
	 * 跳转到分配角色界面
	 */
	//@RequiresPermissions("User:edit")
	@RequestMapping(value = "/getAssignRole", method = {RequestMethod.POST }, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String listAssignRole(final Long userId) {
		final DwzPage page = new DwzPage();
		page.setNumPerPage(Integer.MAX_VALUE);
		// 拿到用户已经有的角色
		final List<UserRole> userRoles = userRoleService.find(userId);
		//未分配的角色
		final List<Role> roles = roleService.findAll(page);

		final Map<String, Object> map = new  HashMap<String,Object>();
		// 返回已经分配的角色和未分配的角色
		map.put("userRoles", userRoles);//已经分配的角色
		map.put("roles", roles);		//所有的角色
		map.put("userId", userId);		//用户ID

		
		return  success(map,SerializerFeature.DisableCircularReferenceDetect);
	}

	/**
	 * 跳转到删除角色的界面
	 */
	//@RequiresPermissions("User:edit")
	@RequestMapping(value = "/userRole", method = {RequestMethod.POST }, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String listUserRole(final Long userId) {
		final Map<String, Object> map = new HashMap<String, Object>();
		final List<UserRole> userRoles = userRoleService.find(userId);
		map.put("userRoles", userRoles);
		return success(  map );
	}

	/**
	 * 删除用户
	 */
	@RequiresPermissions("User:edit")
	@RequestMapping(value = "/delete/userRole/{userRoleId}", method = { RequestMethod.POST })
	@ResponseBody
	public void deleteUserRole(@PathVariable final Long userRoleId) {
		userRoleService.delete(userRoleId);
	}

	/**
	 * 打开新增用户时选择组织的界面
	 */
	@RequiresPermissions(value = { "User:edit", "User:save" })
	@RequestMapping(value = "/lookup2org", method = { RequestMethod.GET })
	public String lookup(final Map<String, Object> map) {
		final Organization org = organizationService.getTree();
		map.put("org", org);
		return "cms/security/user/lookup_org";
	}

	/**
	 * 获取当前登录的用户
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getCurrentUser", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String getCurrentUser(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute(SecurityConstants.LOGIN_USER);
		for (UserRole item:user.getUserRoles()) {
			item.getRole().setNeedPermission(true);
		}
		return success(user);
	}
	

}
